package com.example.toutiao.ui.activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.toutiao.R;
import com.example.toutiao.db.DatabaseHelper;

//添加文章
public class AddArticleActivity extends AppCompatActivity {

    private EditText edtTitle, edtContent;
    private Button btnAddArticle;
    private DatabaseHelper dbHelper;

    @Override
    @SuppressLint("MissingInflatedId")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_article);
        TextView tabBarTitle = findViewById(R.id.tabBarTitle);
        tabBarTitle.setText("添加文章");
        edtTitle = findViewById(R.id.edtTitle);
        edtContent = findViewById(R.id.edtContent);
        btnAddArticle = findViewById(R.id.btnAddArticle);
        dbHelper = new DatabaseHelper(this);
        // 从 SharedPreferences 获取当前登录的用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String currentUsername = sharedPreferences.getString("username", null);

        // 添加文章按钮点击事件
        btnAddArticle.setOnClickListener(v -> {
            String title = edtTitle.getText().toString();
            String content = edtContent.getText().toString();

            if (title.isEmpty() || content.isEmpty()) {
                Toast.makeText(this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
            } else {
                boolean success = dbHelper.addArticle(currentUsername, title, content);
                if (success) {
                    Toast.makeText(this, "文章添加成功", Toast.LENGTH_SHORT).show();
                    finish();  // 返回设置页面
                } else {
                    Toast.makeText(this, "文章添加失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
